<?php

class GroupsDiscussionController extends FrontEndController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','delete', 'deleteDiscussion',
					'insertcomment', 'deletecomment', 'insertcommentlike', 'deletecommentlike', 'morecomments',
					'getimagesforcomment', 'getvideosforcomment', 'getmusicsforcomment'
				),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($discussion)
	{
		$model = GroupsDiscussion::model()->findByPk($discussion);
		$this->render('view',array(
			'model'=>$model,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new GroupsDiscussion;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['GroupsDiscussion']))
		{
			$model->attributes=$_POST['GroupsDiscussion'];
			if($model->save())
				$this->redirect(array('index','group'=>$_GET['group']));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($discussion)
	{
		$model=$this->loadModel($discussion);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['GroupsDiscussion']))
		{
			$model->attributes=$_POST['GroupsDiscussion'];
			if($model->save())
				$this->redirect(array('view','group'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($discussion)
	{
		$model=$this->loadModel($discussion)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : Yii::app()->request->urlReferrer);
	}
	public function actionDeleteDiscussion($discussion)
	{
		$this->loadModel($discussion)->delete();
	}
	/**
	 * Lists all models.
	 */
	public function actionIndex($group)
	{
		$model = GroupsDiscussion::model()->findAll(
			'group_id=:group',
			array(':group'=>$group)
		);
		$this->render('index',array(
			'model'=>$model,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new GroupsDiscussion('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['GroupsDiscussion']))
			$model->attributes=$_GET['GroupsDiscussion'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}


	// more comments
	public function actionMoreComments(){
		if (Yii::app()->request->isAjaxRequest) {
			if(isset($_GET['discussion'])){

				$parent_id = (isset($_GET['parent_id'])) ? $_GET['parent_id'] : 0;
				$offset = (isset($_GET['offset'])) ? $_GET['offset'] : 0;
				$limit = (isset($_GET['limit'])) ? $_GET['limit'] : 0;
				
				$comments=GroupsDiscussioonComments::model()->findAll(array(
					'order'=> 'id DESC',
					'limit'=> $limit,
					'offset'=> $offset,
					'condition'=>'discussion_id=:discussion_id AND parent_id=:parent_id',
					'params'=>array(':discussion_id'=>$_GET['discussion'], ':parent_id'=>$parent_id)
				));
				
				$this->renderPartial('_commentList',array(
					'comments'=>$comments,
					'countComments' => (isset($_GET['countComments'])) ? $_GET['countComments'] : 0,
					'parent_id' => $parent_id,
					'offset' => $offset + $limit,
					'limit' => $limit
				));
			}
		}else{
			$this->redirect(Yii::app()->createUrl('groupsDiscussion/view', array('discussion'=>Yii::app()->request->getParam('discussion'))));
		}
	}
	
	
	// add comment
    public function actionInsertComment()
    {
    	if (Yii::app()->request->isAjaxRequest) {
	    	$data = array();
	    	
	        if(isset($_POST['text'])){
	        	$data['text'] = $_POST['text'];
	        }else{
	        	$data['text'] = '';
	        } 
	        
	        if(isset($_GET['discussion'])){
	        	$data['id'] = $_GET['discussion'];
	        }else{
	        	$data['id'] = 0;
	        }       
	   
	        if(isset($_GET['parent_id'])){
	        	$data['parent_id'] = $_GET['parent_id'];
	        }else{
	        	$data['parent_id'] = 0;
	        }   

	        if(isset($_POST['images'])){
	        	$images = explode(",", $_POST['images']);
	        }else{
	        	$images = 0;
	        }	

	        if(isset($_POST['videos'])){
	        	$videos = explode(",", $_POST['videos']);
	        }else{
	        	$videos = 0;
	        }	        
	        
	        if(isset($_POST['musics'])){
	        	$musics = explode(",", $_POST['musics']);
	        }else{
	        	$musics = 0;
	        }
	        	        
	        if($data['id']){
	        	$make = new GroupsDiscussionComments;
	        	$make->text = $data['text'];
	        	$make->discussion_id = $data['id'];
	        	$make->user_id = Yii::app()->user->id;
	        	$make->parent_id = $data['parent_id'];
	        	$make->crdate = date("Y-m-d H:i:s");
	        	$make->save();

	        	$makeDiscussion = GroupsDiscussion::model()->findByPk($make->discussion_id);
	        	$makeDiscussion->last_user = $make->user_id;
	        	$makeDiscussion->update = $make->crdate;
	        	$makeDiscussion->save();
	        	
	        	$data['comment_id'] =  $make->getPrimaryKey();
	        	
	        	$data['images'] = array();
	        	
	        	if($images){
	        		foreach($images as $image_id){
	        			if($image_id){
	   		     			$make = new GroupsDiscussionCommentsPhotos;
	   		     			$make->discussion_comment_id = $data['comment_id'];
	   		     			$make->photo_id = $image_id;
	   		     			
	   		     			$make->save();
	   		     			
	   		     			$data['images'][] = Photos::model()->findByPk($image_id);
	        			}
	        		}
	        	}
	        	
	        	$data['videos'] = array();
	        	
	        	if($videos){
	        		foreach($videos as $video_id){
	        			if($video_id){
	        				$make = new GroupsDiscussionCommentsVideos;
	        				$make->discussion_comment_id = $data['comment_id'];
	        				$make->video_id = $video_id;
	        	
	        				$make->save();
	        	
	        				$data['videos'][] = Video::model()->findByPk($video_id);
	        			}
	        		}
	        	}	 

	        	$data['musics'] = array();
	        	
	        	if($musics){
	        		foreach($musics as $music_id){
	        			if($music_id){
	        				$make = new GroupsDiscussionCommentsMusics;
	        				$make->discussion_comment_id = $data['comment_id'];
	        				$make->music_user_id = $music_id;
	        				
	        				$make->save();

							$data['musics'][] = MusicUser::model()->findByPk($music_id);
	        			}
	        		}
	        	}	        	
	        	
	        	$user_info = Users::model()->findByPk(Yii::app()->user->id);

	        	// $email_to = Users::model()->findByPk( $data['id'], array('select' => 'full_name, email, comment_notification, last_visit') );
	        	$email_to = GroupsDiscussion::model()->findByPk( $make->discussion_id )->user;
				if( ($email_to->comment_notification == 1) && ($email_to->last_visit < date("Y-m-d H:i:s", time() - 15*60)) ) 
				{
					Yii::app()->getModule('email');
					$email = new Email;
					$email->from = $user_info->email;
					$email->subject = 'Вчечне';
					$email->layout = 'common';
					$email->type = 'text/html';
					$email->to = $email_to->email;
					$email->view = 'main';
					$email->send(array('header' => 'Новая запись на Вашей стене',
						'content' => $email_to->full_name . ', вы получили новое сообещение от '
							. $user_info->full_name . '<br>'
							. $data['text'] . '<br>'
							. 'Получено ' . Yii::app()->dateFormatter->formatDateTime(date("Y-m-d H:i:s"), 'long','short')
					));
					// print_r($email);
				}
	        	
	        	$data['user'] = array(
	        		'name' => $user_info->full_name,
	        		'id' => $user_info->id,
	        		'avatar' => $user_info->avatar
	        	);
		          
	 			$this->renderPartial('_newComment',array(
					'comment'=>$data
				));
	        }
    	}else{
    		$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
    	}
    }	
	
    
    // delete comment
    public function actionDeleteComment(){
    	if (Yii::app()->request->isAjaxRequest) {
    		if(isset($_GET['comment_id'])){
    			GroupsDiscussionComments::model()->deleteAll("id = '" . $_GET['comment_id'] . "'");
    			GroupsDiscussionComments::model()->deleteAll("parent_id = '" . $_GET['comment_id'] . "'");
    			GroupsDiscussionCommentsLikes::model()->deleteAll("discussion_comment_id = '" . $_GET['comment_id'] . "'");    
    			GroupsDiscussionCommentsPhotos::model()->deleteAll("discussion_comment_id = '" . $_GET['comment_id'] . "'");    
    			GroupsDiscussionCommentsMusics::model()->deleteAll("discussion_comment_id = '" . $_GET['comment_id'] . "'");
    			GroupsDiscussionCommentsVideos::model()->deleteAll("discussion_comment_id = '" . $_GET['comment_id'] . "'");
    		} 
    	}else{
    		$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
    	}    	
    }
    
    
    // comment like add
    public function actionInsertCommentLike(){
    	if (Yii::app()->request->isAjaxRequest) {
    		if(isset($_GET['comment_id'])){	
    			$make = new GroupsDiscussionCommentsLikes;
    			$make->discussion_comment_id = $_GET['comment_id'];
    			$make->user_id = Yii::app()->user->id;
    			
    			$make->save();  

    			$comment_like_id = $make->getPrimaryKey();
    			
    			$data['href_dislike'] = Yii::app()->createUrl('groupsDiscussion/deletecommentlike', array('comment_id'=>$_GET['comment_id'], 'comment_like_id'=>$comment_like_id));
    			
    			echo CJSON::encode($data);
    		}
    	}else{
    		$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
    	}    	
    }
    
    // comment like delete
    public function actionDeleteCommentLike(){
    	if (Yii::app()->request->isAjaxRequest) {
    		if(isset($_GET['comment_like_id'])){
    			GroupsDiscussionCommentsLikes::model()->deleteAll("id = '" . $_GET['comment_like_id'] . "'");
    
    			$data['href_like'] = Yii::app()->createUrl('groupsDiscussion/insertcommentlike', array('comment_id'=>$_GET['comment_id']));
    			 
    			echo CJSON::encode($data);
    		}
    	}else{
    		$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
    	}
    }     
    
    // get Users Images For Comment
    public function actionGetImagesForComment(){
    	if (Yii::app()->request->isAjaxRequest) {
    		$albums=Albums::model()->findAll(array(
    			'order'=> 'id DESC',
    			'condition'=>'user_id=:user_id',
    			'params'=>array(':user_id'=>Yii::app()->user->id)
    		));		
    		
    		$images = array();
    		
    		foreach($albums as $album){
    			foreach($album->photos as $photo){
    				$images[] = $photo;
    			}
    		}
    		
			$this->renderPartial('_imageForComment',array(
				'images'=>$images
			));
    	}else{
    		$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
    	}   	
    }
    
    // get Users Videos For Comment
    public function actionGetVideosForComment(){
    	if (Yii::app()->request->isAjaxRequest) {
    		$videos=VideoUser::model()->findAll(array(
    			'order'=> 'id DESC',
    			'condition'=>'user_id=:user_id',
    			'params'=>array(':user_id'=>Yii::app()->user->id)
    		));
    
    		$this->renderPartial('_videoForComment',array(
    			'videos'=>$videos
    		));
    	}else{
    		$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
    	}
    }  

    // get Users Musics For Comment
    public function actionGetMusicsForComment(){
    	if (Yii::app()->request->isAjaxRequest) {
    		
    		$musics=MusicUser::model()->findAll(array(
    			'order'=> 'id DESC',
    			'condition'=>'user_id=:user_id',
    			'params'=>array(':user_id'=>Yii::app()->user->id)
    		));
    
    		$this->renderPartial('_musicForComment',array(
    			'musics'=>$musics
    		));
    	}else{
    		$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
    	}
    }  

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($discussion)
	{
		$model=GroupsDiscussion::model()->findByPk($discussion);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='groups-discussion-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
